<template>
  <div class="app-container">
    <el-card>
      <el-row :gutter="10" class="mb8" type="flex" justify="space-between" style="margin-bottom: 20px">
        <el-col :span="6"><span style="font-size: large">快速查询</span></el-col>
      </el-row>
      <!-- 表单操作项:查询/重置按钮 -->
      <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="110px">
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="timeList"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            type="datetimerange"
            :picker-options="pickerOptions"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            align="right">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="单据号">
          <el-input v-model="queryParams.billsId" placeholder="请输入单据号" clearable></el-input>
        </el-form-item>
        <el-form-item label="业务员">
          <el-input v-model="queryParams.ywy" placeholder="请输入业务员" clearable></el-input>
        </el-form-item>
        <el-form-item style="margin-left: 45px">
          <el-button type="primary" icon="el-icon-search" @click="queryFinishedProductsList">查询</el-button>
          <el-button type="danger" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格部分 -->
    <el-card class="mt20">
      <el-row :gutter="10" class="mb8" type="flex" justify="space-between">
        <el-col :span="6"><span style="font-size: large">收货管理</span></el-col>
      </el-row>
      <el-table :data="goodsList" border class="mt20" height="calc(100vh - 320px)">
        <el-table-column show-overflow-tooltip prop="djbh" label="单据号" align="center" width="150"></el-table-column>
        <el-table-column show-overflow-tooltip prop="bm" label="部门" align="center" width="100"></el-table-column>
        <el-table-column show-overflow-tooltip prop="je" label="金额" align="center"></el-table-column>
        <el-table-column show-overflow-tooltip prop="hsje" label="含税金额" align="center"></el-table-column>
        <el-table-column show-overflow-tooltip prop="kaiprq" label="开票日期" align="center"></el-table-column>
        <el-table-column show-overflow-tooltip prop="ywy" label="业务员" align="center" width="100"></el-table-column>
        <el-table-column show-overflow-tooltip prop="shenhr" label="审核人" align="center"
                         width="100"></el-table-column>
        <el-table-column show-overflow-tooltip prop="shenhrq" label="审核日期" align="center"></el-table-column>
        <el-table-column show-overflow-tooltip prop="fplx" label="发票类型" align="center"></el-table-column>
        <el-table-column show-overflow-tooltip prop="dwmch" label="单位名称" align="center"
                         width="200"></el-table-column>
        <el-table-column label="操作" align="center" width="200">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="goToDetail(scope.row)">查看</el-button>
            <el-button type="primary" size="mini" @click="getAllGoods(scope.row)">收货</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog title="单据详情" :visible="visibleDetial" width="80%" @close="handleCloseDetail" :close-on-click-modal="false">
        <el-table border :data="tableList" height="350px">
          <el-table-column label="单据号" prop="djbh" width="150" align="center"></el-table-column>
          <el-table-column label="商品编号" prop="spbh" width="120" align="center"></el-table-column>
          <el-table-column label="商品名称" prop="spmch" width="120" align="center"></el-table-column>
          <el-table-column label="商品规格" prop="shpgg" width="120" align="center"></el-table-column>
          <el-table-column label="单位" prop="dw" width="60" align="center"></el-table-column>
          <el-table-column label="生产厂家" prop="shengccj" width="120" align="center"></el-table-column>
          <el-table-column label="批准文号" prop="pizhwh" align="center" width="150"></el-table-column>
          <el-table-column label="类别" prop="leibie" width="100" align="center"></el-table-column>
          <!-- 可编辑的实收数量列 -->
          <el-table-column label="实收数量" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.lingsshl"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="应收数量" prop="shl" align="center"></el-table-column>
          <!-- 可编辑的单价列 -->
          <el-table-column label="单价" align="center" width="120">
            <template slot-scope="scope">
              <el-input v-model="scope.row.dj" size="mini"></el-input>
            </template>
          </el-table-column>

          <el-table-column label="采购负责人" prop="cgfzr" align="center" width="100"></el-table-column>
          <el-table-column label="扣率" prop="koul" width="60" align="center"></el-table-column>
          <el-table-column label="计量规格" prop="jlgg" align="center"></el-table-column>
          <el-table-column label="操作" align="center" width="160">
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="mini"
                @click="handleReceiveGoods(scope.row)"
              >收货
              </el-button>
              <el-button
                type="primary"
                size="mini"
                @click="handleRefuseGoods(scope.row)"
              >拒收
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>
      <el-dialog title="拒收详情" :visible="refuseVisible" width="30%" @close="closeRefuse" :close-on-click-modal="false">
        <el-input
          type="textarea"
          :rows="3"
          placeholder="请输入拒收原因"
          v-model="rejectReason"
        ></el-input>
        <div slot="footer" class="dialog-footer">
          <el-button @click="closeRefuse">取消</el-button>
          <el-button type="primary" @click="submitRefuse">确认</el-button>
        </div>
      </el-dialog>
      <div class="block" style="float: right; margin: 20px">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageNum"
                       :page-sizes="[20,50,100,200,500]" :page-size="pageSize"
                       layout="total, sizes, prev, pager, next, jumper"
                       :total="total">
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
import {
  queryErpReceipt,//收货管理
  queryErpReceiptDetail,//查看详情
  confirmReceipt,//批量收货
  confirmReceiptBySpid,//单独收货
  rejectReceiver,//拒收
} from '@/api/storeM/yxl.js'

export default {
  // 用于存储需要加载的字典类型
  data() {
    return {
      refuseVisible: false,//拒收详情
      pageNum: 1, // 当前页
      pageSize: 20, // 每页显示条数
      total: 0, // 总条目数，需从后端返回
      goodsList: [],
      queryParams: {
        billsId: '',
        ywy: '',
      },
      rejectReason: '',//拒收原因
      timeList: [this.getDefaultStartDate(), this.getDefaultEndDate()],
      tableList: [],//详情table
      visibleDetial: false,//收货详情
      rowData:{},//存放详情
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
    };
  },
  created() {
    this.queryFinishedProductsList();
  },
  methods: {
    //拒收操作
    submitRefuse(){
      if(this.rejectReason == ''){
        this.$message({
          type: 'error',
          message: '请填写拒收原因'
        });
        return
      }
      rejectReceiver({
        billsId: this.rowData.djbh,
        spid: this.rowData.spid,
        lingsshl: this.rowData.lingsshl, // 实收数量
        dj: this.rowData.dj,             // 单价
        remark: this.rejectReason,
      }).then(res => {
        this.$message({
          type: 'success',
          message: res.msg
        });
        this.queryFinishedProductsList();
        this.closeRefuse();
      }).catch(err => {
        this.$message({
          type: 'error',
          message: err?.msg || '操作失败'
        });
      });
    },
    //拒收
    handleRefuseGoods(row) {
      this.rowData = row;
      this.refuseVisible = true;
    },
    //关闭拒绝详情
    closeRefuse() {
      this.refuseVisible = false;
      this.rejectReason = '';
    },
    //获取日期
    getDefaultStartDate() {
      const date = new Date()
      date.setMonth(date.getMonth() - 1)
      return this.formatDate(date)
    },
    getDefaultEndDate() {
      return this.formatDate(new Date())
    },
    //格式化日期
    formatDate(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    //查看详情
    goToDetail(row) {
      this.visibleDetial = true;
      queryErpReceiptDetail({billsId: row.djbh}).then(res => {
        this.tableList = res.data;
      })
    },
    //关闭详情
    handleCloseDetail() {
      this.visibleDetial = false;
    },
    //单独收货
    handleReceiveGoods(row) {
      this.$confirm(`确认要进行收货吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        confirmReceiptBySpid({
          billsId: row.djbh,
          spid: row.spid,
          lingsshl: row.lingsshl, // 实收数量
          dj: row.dj,             // 单价
        }).then(res => {
          this.$message.success(res.msg);
          this.goToDetail();
        })
      }).catch(() => {
        this.$message.info('已取消');
      })
    },
    //批量收货
    getAllGoods(row) {
      this.$confirm(`确认要进行批量收货吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        confirmReceipt({
          billsId: row.djbh
        }).then(res => {
          this.$message.success(res.msg);
          this.queryFinishedProductsList();
        })
      }).catch(() => {
        this.$message.info('已取消');
      })
    },
    //获取的单据
    queryFinishedProductsList() {
      if (this.timeList && this.timeList[0]) {
        this.queryParams.startDate = this.timeList[0];
      } else {
        delete this.queryParams.startDate; // 如果时间为空，则删除该字段
      }
      if (this.timeList && this.timeList[1]) {
        this.queryParams.endDate = this.timeList[1];
      } else {
        delete this.queryParams.endDate; // 如果时间为空，则删除该字段
      }
      let params = {
        pageSize: this.pageSize,
        pageNum: this.pageNum,
        ...this.queryParams,
      }
      queryErpReceipt(params).then(res => {
        this.goodsList = res.data.rows;
        this.total = res.data.total;
      })
    },
    // 页大小变化
    handleSizeChange(newPageSize) {
      this.pageSize = newPageSize;
      this.pageNum = 1; // 重置为第一页
      this.queryFinishedProductsList(); // 重新查询
    },

    // 当前页变化
    handleCurrentChange(newPage) {
      this.pageNum = newPage;
      this.queryFinishedProductsList(); // 重新查询
    },

    /**
     * 重置表单操作
     * 将所有查询条件还原为初始状态
     */
    resetQuery() {
      this.queryParams = {
        billsId: '',
        ywy: '',
      };
      this.timeList = [this.getDefaultStartDate(), this.getDefaultEndDate()];
      this.queryFinishedProductsList();
    },
  },
};
</script>

<style scoped>
/* 主容器样式：设置内边距，避免紧贴页面边缘 */
.app-container {
  padding: 20px;
}

/* 卡片样式：为每个表单块设置外边距，提升视觉效果 */
.el-card {
  margin-bottom: 20px;
}

.btn el-button {
  margin-bottom: 20px;
}
</style>
